# coding:utf-8

from wtforms import (
    StringField, TextAreaField, BooleanField, SubmitField,
)
from wtforms_components import (
    IntegerField, DecimalField,
    DateTimeField, read_only, SelectField
)
from wtforms.validators import Optional, DataRequired, NumberRange

from app.constant import get_tomorrow_fifteen_oclock
from .constant import (
    DemandCate, DemandMalf, DemandType,
    DemandSurr, DemandColor, DemandTag,
    DemandStatus, DemandNoticeWay,
    DemandSource, AreaType, SEMGroup,
    DemandClientSource, OperateResult, OperatedStatus
)

from app.auth.models import AdminUser
from ..forms import (
    WphForm, NonValidatingSelectField, NonValidatingRadioField,
    NotChoices, MyDateTimeField,
)
from app.ccws.constant import CallReason
from .models import Area
from app.constant import Choice


class BaseDemandForm(WphForm):
    """
    新增项目与编辑项目表单基类
    """

    prov = SelectField('省份', validators=[DataRequired()])
    cate = NonValidatingSelectField(
        '需求分类', coerce=int,
        choices=DemandCate.to_options(),
        validators=[Optional()],
    )
    malf = NonValidatingSelectField(
        '故障分类', coerce=int,
        choices=DemandMalf.to_options(),
        validators=[Optional()],
    )
    type = NonValidatingSelectField(
        '屏幕类型', coerce=int,
        choices=DemandType.to_options(),
        validators=[Optional()],
    )
    surr = NonValidatingSelectField(
        '使用场地', coerce=int,
        choices=DemandSurr.to_options(),
        validators=[Optional()],
    )
    color = NonValidatingSelectField(
        '颜色', coerce=int,
        choices=DemandColor.to_options(),
        validators=[Optional()],
    )
    addr = StringField('详细地址', validators=[Optional()])
    span = StringField('间距', validators=[Optional()])
    size = DecimalField('面积(平米)', validators=[Optional()])
    budget = DecimalField('预算', validators=[Optional()])
    status = NonValidatingSelectField(
        '状态', coerce=int,
        choices=DemandStatus.to_options(),
        validators=[Optional()],
    )
    tag = NonValidatingSelectField(
        '项目标签', coerce=int,
        choices=DemandTag.to_options(),
        validators=[Optional()]
    )
    source = NonValidatingSelectField(
        '项目来源',
        choices=NotChoices + DemandSource.to_options(),
        validators=[Optional()]
    )
    remark = TextAreaField('客户要求', validators=[Optional()])
    history_admin_remark = TextAreaField('历史内部备注', validators=[Optional()])
    admin_remark = TextAreaField('内部备注', validators=[Optional()])
    audio_sensitive = BooleanField('录音敏感', validators=[Optional()], default=False)
    bid_start_point = IntegerField('竞价起拍点', default=10, validators=[NumberRange(min=1)])

    publish_remark = TextAreaField('发布原因', validators=[Optional()])

    def __init__(self, *args, **kwargs):
        super(BaseDemandForm, self).__init__(*args, **kwargs)
        self.prov.choices = NotChoices + \
            [
                (area.name, area.name)
                for area in Area.query.filter_by(type=AreaType.PROV.value).order_by(Area.id.asc())
            ]
        self.prov.default = NotChoices[0][0]
        read_only(self.history_admin_remark)
        read_only(self.publish_remark)


class DetailDemandForm(BaseDemandForm):
    """
    项目详情表单
    """

    id = IntegerField('需求ID', validators=[Optional()])
    uid = IntegerField('用户ID', validators=[Optional()])
    user_mobile = IntegerField('用户手机', validators=[Optional()])

    user_nickname = StringField('用户昵称', validators=[Optional()])

    city = SelectField('城市', validators=[DataRequired()])

    # 需要在view中初始化录音选项
    audio_id = NonValidatingRadioField(
        '关联录音', coerce=int, validators=[Optional()],
    )

    # 项目完成图片
    finish_img_id = NonValidatingRadioField(
        '项目申报', coerce=int, validators=[Optional()],
    )

    edit_created_at = MyDateTimeField('创建时间', validators=[Optional()],)
    edit_published_at = MyDateTimeField('发布时间', validators=[Optional()],)

    submit = SubmitField('保存')

    def __init__(self, *args, **kwargs):
        super(DetailDemandForm, self).__init__(*args, **kwargs)
        read_only(self.id)
        read_only(self.uid)
        read_only(self.user_mobile)

        self.city.choices = NotChoices + \
            [
                (area.name, area.name)
                for area in Area.query.filter_by(type=AreaType.CITY.value).order_by(Area.id.asc())
            ]
        self.city.default = NotChoices[0][0]


class PublishDemandForm(WphForm):
    """
    发布项目表单
    """
    id = IntegerField('需求ID', validators=[Optional()])
    uid = IntegerField('用户ID', validators=[Optional()])
    user_mobile = IntegerField('用户手机', validators=[Optional()])
    user_nickname = StringField('用户昵称', validators=[Optional()])
    published_count = IntegerField('累计发布次数', validators=[Optional()])

    # 通知方式：不通知，仅发短信，仅发微信，优先微信通知
    notice_way = NonValidatingSelectField(
        '通知形式',
        coerce=int,
        choices=[
            DemandNoticeWay.NO_NOTICE.args,
            DemandNoticeWay.JUST_WX.args,
        ],
        validators=[Optional()],
        default=DemandNoticeWay.JUST_WX.value,
    )
    # 通知是否扣费
    notice_pay = BooleanField('需扣费', default=True)
    # 仅通知(不递增累计发布次数)
    only_notify = BooleanField('仅通知(不递增累计发布次数)', default=False)
    # 是否包含未绑定用户
    contain_no_bind = BooleanField('包含未绑定微信用户', default=False)
    # 当前项目状态
    current_demand_status = StringField('当前项目状态', validators=[Optional()])
    # 项目状态
    demand_status = SelectField(
        '新项目状态', validators=[Optional()], coerce=int,
        choices=[
            (0, '--请选择项目状态--'),
            DemandStatus.BRONZE_MEDAL_DISCOUNT.args,
            DemandStatus.DISPATCHING.args,
            DemandStatus.MASTER_DISPATCHING.args,
            DemandStatus.ONGOING.args,
            DemandStatus.SECOND_ONGOING.args,
            DemandStatus.FREE_ONGOING.args,
        ]
    )
    # 发布理由
    current_publish_remark = TextAreaField('发布理由', validators=[Optional()])

    # 回访信息
    next_outbound = BooleanField('设置回访', default=False, validators=[Optional()])
    next_outbound_schedule_time = DateTimeField(
        '回访时间',
        validators=[Optional()],
        default=get_tomorrow_fifteen_oclock,
    )
    next_outbound_call_reason = NonValidatingSelectField(
        '外呼原因', coerce=int, choices=CallReason.to_options(),
        validators=[Optional()], default=CallReason.VISIT_CALLBACK.value,
    )
    # 派单人数
    dispatch_count = IntegerField('派单人数', default=3, validators=[Optional()])

    def __init__(self, *args, **kwargs):
        super(PublishDemandForm, self).__init__(*args, **kwargs)
        read_only(self.id)
        read_only(self.uid)
        read_only(self.user_mobile)
        read_only(self.published_count)
        read_only(self.current_demand_status)


class CreateDemandForm(BaseDemandForm):
    """
    新建项目表单
    """

    user_mobile = StringField('发布者手机号', validators=[Optional()])
    user_nickname = StringField('发布者昵称', validators=[Optional()])
    city = SelectField('城市', validators=[DataRequired()])

    # 需要在view中初始化录音选项
    audio_id = NonValidatingRadioField(
        '关联录音', coerce=int, validators=[Optional()],
    )

    submit = SubmitField('保存')

    def __init__(self, *args, **kwargs):
        super(CreateDemandForm, self).__init__(*args, **kwargs)
        # 新建项目状态必定为草稿，且不可修改
        self.status.choices = [(DemandStatus.DRAFT.value, '草稿')]
        self.status.default = DemandStatus.DRAFT.value
        read_only(self.status)
        self.city.choices = NotChoices + \
            [
                (area.name, area.name)
                for area in Area.query.filter_by(type=AreaType.CITY.value).order_by(Area.id.asc())
            ]
        self.city.default = NotChoices[0][0]


class SearchDemandForm(WphForm):
    """
    搜索项目表单
    """

    id = IntegerField('需求ID', validators=[Optional()])
    uid = IntegerField('用户ID', validators=[Optional()])
    user_phone = StringField('发布者手机号', validators=[Optional()])
    prov = NonValidatingSelectField(
        '省份', validators=[Optional()], default=NotChoices[0][0]
    )
    cate = NonValidatingSelectField(
        '需求分类', coerce=int,
        choices=NotChoices + DemandCate.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    malf = NonValidatingSelectField(
        '故障分类', coerce=int,
        choices=NotChoices + DemandMalf.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    type = NonValidatingSelectField(
        '屏幕类型', coerce=int,
        choices=NotChoices + DemandType.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    surr = NonValidatingSelectField(
        '使用场地', coerce=int,
        choices=NotChoices + DemandSurr.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    color = NonValidatingSelectField(
        '颜色', coerce=int,
        choices=NotChoices + DemandColor.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    status = NonValidatingSelectField(
        '状态', coerce=int,
        choices=NotChoices + DemandStatus.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    tag = NonValidatingSelectField(
        '项目标签', coerce=int,
        choices=NotChoices + DemandTag.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    source = NonValidatingSelectField(
        '项目来源',
        choices=NotChoices + DemandSource.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    admin_remark = StringField('管理员备注', validators=[Optional()])
    remark = StringField('客户要求', validators=[Optional()])
    admin_id = NonValidatingSelectField(
        '客服',
        validators=[Optional()], default=NotChoices[0][0]
    )
    created_at_begin = MyDateTimeField('最早创建时间', validators=[Optional()],)
    created_at_end = MyDateTimeField('最晚创建时间', validators=[Optional()],)
    published_at_begin = MyDateTimeField('最早发布时间', validators=[Optional()],)
    published_at_end = MyDateTimeField('最晚发布时间', validators=[Optional()],)
    is_for_gold = NonValidatingSelectField(
        '金牌项目', coerce=int,
        choices=NotChoices + Choice.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    has_audio = BooleanField('含录音', default=False, validators=[Optional()])
    robot_win = NonValidatingSelectField(
        '砸手里的', coerce=int,
        choices=NotChoices + [('1', '所有'), ('2', '全砸手里'), ('3', '半砸手里')],
        validators=[Optional()], default=NotChoices[0][0]
    )
    ignore_invalid = BooleanField('PP不想看无效单', default=False, validators=[Optional()])

    submit = SubmitField('查询')

    def __init__(self, *args, **kwargs):
        super(SearchDemandForm, self).__init__(*args, **kwargs)
        self.prov.choices = NotChoices + \
            [
                (area.name, area.name)
                for area in Area.query.filter_by(type=1).order_by(Area.id.asc())
            ]
        self.admin_id.choices = NotChoices + \
            [
                (admin.id, admin.nickname)
                for admin in AdminUser.query.filter(
                    AdminUser.agent_id > 0
                ).order_by(AdminUser.id.asc())
            ]


class SearchDemandForSemForm(WphForm):
    """
    add by zhouhl 2017-11-02
    搜索sem引入的项目表单
    """
    id = IntegerField('需求ID', validators=[Optional()])
    uid = IntegerField('用户ID', validators=[Optional()])
    user_phone = StringField('发布者手机号', validators=[Optional()])

    sem_source = StringField('sem来源', validators=[Optional()])
    sem_plan = StringField('sem计划', validators=[Optional()])
    sem_unit = StringField('sem单元', validators=[Optional()])
    sem_keyword = StringField('sem_keyword', validators=[Optional()])
    sem_phone_number = NonValidatingSelectField(
        '呼入来路',
        choices=NotChoices + SEMGroup.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    status = NonValidatingSelectField(
        '状态', coerce=int,
        choices=NotChoices + DemandStatus.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    source = NonValidatingSelectField(
        '项目来源',
        choices=NotChoices + DemandSource.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    created_at_begin = MyDateTimeField('最早创建时间', validators=[Optional()],)
    created_at_end = MyDateTimeField('最晚创建时间', validators=[Optional()],)
    published_at_begin = MyDateTimeField('最早发布时间', validators=[Optional()], )
    published_at_end = MyDateTimeField('最晚发布时间', validators=[Optional()], )


class UserDemandForm(WphForm):
    """
    用户-项目关联form
    """

    cate = NonValidatingSelectField(
        '需求分类', coerce=int,
        choices=DemandCate.to_options(),
        validators=[Optional()],
    )
    malf = NonValidatingSelectField(
        '故障分类', coerce=int,
        choices=DemandMalf.to_options(),
        validators=[Optional()],
    )
    demand_type = NonValidatingSelectField(
        '屏幕类型', coerce=int,
        choices=DemandType.to_options(),
        validators=[Optional()],
    )
    surr = NonValidatingSelectField(
        '使用场地', coerce=int,
        choices=DemandSurr.to_options(),
        validators=[Optional()],
    )
    color = NonValidatingSelectField(
        '颜色', coerce=int,
        choices=DemandColor.to_options(),
        validators=[Optional()],
    )
    span = StringField('间距', validators=[Optional()])
    size = DecimalField('面积(平米)', validators=[Optional()])
    budget = DecimalField('预算', validators=[Optional()])
    demand_status = NonValidatingSelectField(
        '状态', coerce=int,
        choices=[
            DemandStatus.DRAFT.args,
            DemandStatus.UNCHECKED.args,
        ],
        validators=[Optional()],
    )
    tag = NonValidatingSelectField(
        '项目标签', coerce=int,
        choices=DemandTag.to_options(),
        validators=[Optional()]
    )
    source = NonValidatingSelectField(
        '项目来源',
        choices=NotChoices + DemandSource.to_options(),
        validators=[Optional()]
    )
    demand_remark = TextAreaField('客户要求', validators=[Optional()])
    admin_remark = TextAreaField('内部备注', validators=[Optional()])


class SearchBidSupplierForm(WphForm):
    """
    """
    demand_id = IntegerField('需求ID', validators=[Optional()])
    bid_win_at_begin = MyDateTimeField('中标起始时间', validators=[Optional()], )
    bid_win_at_end = MyDateTimeField('中标结束时间', validators=[Optional()], )


class SearchDemandClientForm(WphForm):
    """
    created by chenhj at 15/01/2018

    """
    user_mobile = StringField('客户电话', validators=[Optional()])
    user_nickname = StringField('客户昵称', validators=[Optional()])
    sem_path = StringField('推广来源', validators=[Optional()])
    client_source = NonValidatingSelectField(
        '来源',
        choices=NotChoices + DemandClientSource.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    operate_time_filter = NonValidatingSelectField(
        '处理时间',
        choices=NotChoices + [
            ('1', '5分钟'), ('2', '10分钟'), ('3', '20分钟'),
            ('4', '30分钟'), ('5', '1小时'), ('6', '其他')
        ],
        validators=[Optional()], default=NotChoices[0][0]
    )
    last_visit_time_begin = DateTimeField('最早访问时间', validators=[Optional()])
    last_visit_time_end = DateTimeField('最晚访问时间', validators=[Optional()])
    operate_result = NonValidatingSelectField(
        '结果',
        choices=NotChoices + OperateResult.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    sem_plan = StringField('sem计划', validators=[Optional()])
    sem_unit = StringField('sem单元', validators=[Optional()])
    sem_keyword = StringField('sem_keyword', validators=[Optional()])


class SearchRenewableDemandForm(WphForm):
    """
    搜索项目表单
    """

    id = IntegerField('需求ID', validators=[Optional()])
    uid = IntegerField('用户ID', validators=[Optional()])
    user_phone = StringField('发布者手机号', validators=[Optional()])
    prov = NonValidatingSelectField(
        '省份', validators=[Optional()], default=NotChoices[0][0]
    )
    cate = NonValidatingSelectField(
        '需求分类', coerce=int,
        choices=NotChoices + DemandCate.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    malf = NonValidatingSelectField(
        '故障分类', coerce=int,
        choices=NotChoices + DemandMalf.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    type = NonValidatingSelectField(
        '屏幕类型', coerce=int,
        choices=NotChoices + DemandType.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    surr = NonValidatingSelectField(
        '使用场地', coerce=int,
        choices=NotChoices + DemandSurr.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    color = NonValidatingSelectField(
        '颜色', coerce=int,
        choices=NotChoices + DemandColor.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    status = NonValidatingSelectField(
        '状态', coerce=int,
        choices=NotChoices + DemandStatus.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    tag = NonValidatingSelectField(
        '项目标签', coerce=int,
        choices=NotChoices + DemandTag.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    source = NonValidatingSelectField(
        '项目来源',
        choices=NotChoices + DemandSource.to_options(),
        validators=[Optional()], default=NotChoices[0][0]
    )
    admin_remark = StringField('管理员备注', validators=[Optional()])
    remark = StringField('客户要求', validators=[Optional()])
    admin_id = NonValidatingSelectField(
        '客服',
        validators=[Optional()], default=NotChoices[0][0]
    )
    operated_status = NonValidatingSelectField(
        '处理结果',
        choices=[(-1, '')] + OperatedStatus.to_options(),
        coerce=int,
        validators=[Optional()]
    )
    created_at_begin = MyDateTimeField('最早创建时间', validators=[Optional()],)
    created_at_end = MyDateTimeField('最晚创建时间', validators=[Optional()],)
    published_at_begin = MyDateTimeField('最早发布时间', validators=[Optional()],)
    published_at_end = MyDateTimeField('最晚发布时间', validators=[Optional()],)
    has_audio = BooleanField('含录音', default=False, validators=[Optional()])

    submit = SubmitField('查询')

    def __init__(self, *args, **kwargs):
        super(SearchRenewableDemandForm, self).__init__(*args, **kwargs)
        self.prov.choices = NotChoices + \
            [
                (area.name, area.name)
                for area in Area.query.filter_by(type=1).order_by(Area.id.asc())
            ]
        self.admin_id.choices = NotChoices + \
            [
                (admin.id, admin.nickname)
                for admin in AdminUser.query.filter(
                    AdminUser.agent_id > 0
                ).order_by(AdminUser.id.asc())
            ]


class TrainingDemandForm(WphForm):

    mobiles = TextAreaField('赠送人手机号', validators=[Optional()])
